package com.csu.csumall.controller.frontend;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.csumall.VO.CartVO;
import com.csu.csumall.VO.OrderDetailVO;
import com.csu.csumall.VO.OrderItemVO;
import com.csu.csumall.common.CartStatus;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.OrderStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.Cart;
import com.csu.csumall.entity.Order;
import com.csu.csumall.entity.OrderItem;
import com.csu.csumall.entity.User;
import com.csu.csumall.service.*;
import com.csu.csumall.util.AlipayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.csu.csumall.common.Constant.ORIGIN;

@Slf4j
@RestController
@RequestMapping("/api/order")
@CrossOrigin(origins = ORIGIN)
public class OrderController {

    private final IOrderService orderService;
    private final IOrderItemService orderItemService;
    private final IOrderItemVOService orderItemVOService;
    private final IOrderDetailVOService orderDetailVOService;
    private final ICartService cartService;
    private final ICartVOService cartVOService;
    private final AlipayUtil alipayUtil;

    @Autowired
    public OrderController(IOrderService orderService, IOrderItemService orderItemService,
                           IOrderItemVOService orderItemVOService, IOrderDetailVOService orderDetailVOService, ICartService cartService, ICartVOService cartVOService, AlipayUtil alipayUtil) {
        this.orderService = orderService;
        this.orderItemService = orderItemService;
        this.orderItemVOService = orderItemVOService;
        this.orderDetailVOService = orderDetailVOService;
        this.cartService = cartService;
        this.cartVOService = cartVOService;
        this.alipayUtil = alipayUtil;
    }

    /**
     * 获取订单列表
     * @param user
     * @param status
     * @param page
     * @param size
     * @return OrderItemVO
     */
    @GetMapping(produces = "application/json")
    public ResponseEntity<UniformResponse<List<OrderItemVO>>> list(@AuthenticationPrincipal User user,
                                                       @RequestParam(value = "status", defaultValue = "-1") Integer status,
                                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                       @RequestParam(value = "size", defaultValue = "20") Integer size) {

        if (null == user) {
            return new ResponseEntity<>(UniformResponse.createForError("单号与用户不符"), HttpStatus.UNAUTHORIZED);
        }

        List<OrderItemVO> orderItemVOList;

        if (status == OrderStatus.DEFAULT.getValue()) {
            orderItemVOList = orderItemVOService.list(user, page, size);
        } else {
            orderItemVOList = orderItemVOService.list(user, status, page, size);
        }

        return new ResponseEntity<>(UniformResponse.createForSuccess(orderItemVOList), HttpStatus.OK);
    }

    /**
     * 获取订单详细信息
     * @param id order.id
     * @return
     */
    @GetMapping(value = "{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<OrderDetailVO>> detail(@AuthenticationPrincipal User user,
                                                             @PathVariable(value = "id", required = true) Integer id) {

        if (!orderService.isAuthenticated(user, id)) {
            return new ResponseEntity<>(UniformResponse.createForError("单号与用户不符"), HttpStatus.UNAUTHORIZED);
        }

        Order order = orderService.getById(id);
        OrderDetailVO orderDetailVO = orderDetailVOService.getOne(user, order.getOrderNo());

        return new ResponseEntity<>(UniformResponse.createForSuccess(orderDetailVO), HttpStatus.OK);
    }

    @GetMapping(value = "query")
    public ResponseEntity<UniformResponse<String>> query(@RequestParam(value = "outTradeNo") String outTradeNo) {
        log.info("outTradeNo: " + outTradeNo);
        String q = alipayUtil.query(outTradeNo);
        return new ResponseEntity<>(UniformResponse.createForSuccess(q), HttpStatus.OK);
    }

    @GetMapping(value = "fake")
    public ResponseEntity<UniformResponse<Map<String, String>>> fake(@AuthenticationPrincipal User user) {
        // 获取选择的cart
        List<CartVO> cartVOList = cartVOService.listChecked(user.getId());
        // 创建订单 获取订单号
        Order order = new Order(user.getId());
        BigInteger orderNo = order.getOrderNo();
        // 存储订单
//        boolean saveOrderFlag = orderService.save(order);

        // 存储orderItem
//        List<OrderItem> orderItemList = cartVOList.stream().map(cartVO ->
//                new OrderItem(cartVO, user.getId(), orderNo)
//        ).collect(Collectors.toList());
//        orderItemService.saveBatch(orderItemList);
        // 删除购物车
//        Cart cart = new Cart();
//        cart.setStatus(ItemStatus.DISABLE.getValue());
//        boolean deleteCheckedCartFlag = cartService.update(cart,
//                new QueryWrapper<Cart>().eq("user_id", user.getId())
//                        .eq("checked", CartStatus.CHECKED.getValue()));


        float amount = ((float) cartVOList.stream().mapToInt(cartVO -> cartVO.getPrice() * cartVO.getQuantity()).sum()) / 100;
        NumberFormat formatter = new DecimalFormat("0.00");
        String amountStr = formatter.format(amount);

        String subject = cartVOList.stream().map(CartVO::getProductName).toString();


        // 支付宝preCreate
        AlipayTradePrecreateResponse response = alipayUtil.preCreate(orderNo.toString(), amountStr, subject);
        String qrCode = response.getQrCode();
        String outTradeNo = response.getOutTradeNo();
        Map<String, String> map = new HashMap<>();
        map.put("qrCode", qrCode);
        map.put("outTradeNo", outTradeNo);


        return new ResponseEntity<>(UniformResponse.createForSuccess(map), HttpStatus.OK);
    }

    /**
     * 从购物车提交订单
     * @return
     */
    @PostMapping(value = "cart", produces = "application/json")
    public ResponseEntity<UniformResponse<String>> checkoutCart(@AuthenticationPrincipal User user) {

        // 获取选择的cart
        List<CartVO> cartVOList = cartVOService.listChecked(user.getId());
        // 创建订单 获取订单号
        Order order = new Order(user.getId());
        BigInteger orderNo = order.getOrderNo();
        // 存储订单
        boolean saveOrderFlag = orderService.save(order);

        // 存储orderItem
        List<OrderItem> orderItemList = cartVOList.stream().map(cartVO ->
            new OrderItem(cartVO, user.getId(), orderNo)
        ).collect(Collectors.toList());
        orderItemService.saveBatch(orderItemList);
        // 删除购物车
        Cart cart = new Cart();
        cart.setStatus(ItemStatus.DISABLE.getValue());
        boolean deleteCheckedCartFlag = cartService.update(cart,
                new QueryWrapper<Cart>().eq("user_id", user.getId())
                        .eq("checked", CartStatus.CHECKED.getValue()));


        float amount = ((float) cartVOList.stream().mapToInt(cartVO -> cartVO.getPrice() * cartVO.getQuantity()).sum()) / 100;
        NumberFormat formatter = new DecimalFormat("0.00");
        String amountStr = formatter.format(amount);

        String subject = cartVOList.stream().map(CartVO::getProductName).toString();


        // 支付宝preCreate
        AlipayTradePrecreateResponse response = alipayUtil.preCreate(orderNo.toString(), amountStr, subject);
        String qrCode = response.getQrCode();


        return saveOrderFlag && deleteCheckedCartFlag ?
        new ResponseEntity<>(UniformResponse.createForSuccess(qrCode), HttpStatus.OK)
        :
        new ResponseEntity<>(UniformResponse.createForError("创建失败"), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // TODO
    @PutMapping
    public ResponseEntity<UniformResponse<Object>> put(@AuthenticationPrincipal User user,
                                                       @RequestBody(required = true) Order order) {
        if (!orderService.isAuthenticated(user, order.getId())) {
            return new ResponseEntity<>(UniformResponse.createForError("单号与用户不符"), HttpStatus.UNAUTHORIZED);
        }

        order.updateOrder();

        return orderService.updateById(order) ?
        new ResponseEntity<>(UniformResponse.createForSuccess(order), HttpStatus.CREATED)
        :
        new ResponseEntity<>(UniformResponse.createForError("更新失败"), HttpStatus.INTERNAL_SERVER_ERROR);
    }


}
